/*
 * Flight.cpp
 *
 *  Created on: May 6, 2014
 *      Author: alexander
 */

#include "Flight.h"

#include "Downloader.h"
#include "Poco/StringTokenizer.h"
#include "Poco/String.h"
#include "Poco/DateTime.h"
#include "Poco/Timespan.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/NumberParser.h"

Flight::Flight(double price, const std::string& currency)
{
	price_ = price;
	currency_ = currency;
}

Flight Flight::obtainFlightFromWeb(const std::string& where, const std::string& when)
{
	const std::string dateMarker = "dateFrom: ";
	const std::string valueMarker = "value: ";
	const std::string currencyMarker = "currencySymbol: ";

	std::vector<std::string> webPage = Downloader::fetchData("http://ryanair.com/en/cheap-flights/" + where + "/?out-date=" + when);
	for (auto it = webPage.begin(); it != webPage.end(); ++it)
	{
		std::size_t pos = (*it).find(dateMarker);
		if (pos != std::string::npos)
		{
			Poco::StringTokenizer t((*it).substr(pos + dateMarker.size()), "TZ\",",
					Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);

			if (t.count() != 2)
			{
//				std::cout << "Could not parse (dateMarker):" << std::endl;
//				std::cout << *it << std::endl;
				continue;
			}
			if (!when.compare(t[0]))
			{
				it += 2;
				pos = (*it).find(valueMarker);
				if (pos != std::string::npos)
				{
					Poco::StringTokenizer t((*it).substr(pos + valueMarker.size()), "\",",
							Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);
					if (t.count() != 1)
					{
//						std::cout << "Could not parse(valueMarker):" << std::endl;
//						std::cout << *it << std::endl;
						continue;
					}
//					std::cout << "Found a flight on " << when << " for " << t[0] << std::endl;
					double price = Poco::NumberParser::parseFloat(t[0]);

					it += 3;
					pos = (*it).find(currencyMarker);
					if (pos != std::string::npos)
					{
						Poco::StringTokenizer t((*it).substr(pos + currencyMarker.size()), "\",",
								Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);
						if (t.count() != 1)
						{
//							std::cout << "Could not parse:" << std::endl;
//							std::cout << *it << std::endl;
							continue;
						}
						return Flight(price, t[0]);
					}
				}
			}
		}
	}
	return Flight();
}
